#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import threading
import time
import logging
from http.client import HTTPConnection

from app import create_app, db

HOST = '127.0.0.1'
PORT = 3000
WAIT_CYCLES = 80
WAIT_INTERVAL = 0.5

logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%H:%M:%S'
)

def start_flask():
    app = create_app()
    with app.app_context():
        db.create_all()
    app.run(host=HOST, port=PORT, debug=False, use_reloader=False)

def is_backend_ready():
    try:
        conn = HTTPConnection(HOST, PORT, timeout=1)
        conn.request('HEAD', '/')
        resp = conn.getresponse()
        resp.read()
        conn.close()
        return True
    except Exception:
        return False

def wait_for_backend():
    logging.info(f"等待后端就绪（最多 {WAIT_CYCLES*WAIT_INTERVAL:.1f}s）…")
    for _ in range(WAIT_CYCLES):
        if is_backend_ready():
            logging.info("后端已就绪！")
            return True
        time.sleep(WAIT_INTERVAL)
    return False

if __name__ == '__main__':
    # 1. 启动 Flask 后端（daemon线程，PyWebView关闭时自动清理）
    flask_thread = threading.Thread(target=start_flask, daemon=True)
    flask_thread.start()

    # 2. 等待后端就绪
    if not wait_for_backend():
        logging.critical("后端启动超时，程序退出")
        sys.exit(1)

    # 3. 用 PyWebView 打开窗口（窗口关闭后整个 Python/Flask 进程自动终止，无残留！）
    try:
        import webview
    except ImportError:
        logging.critical("未安装 pywebview，请先 pip install pywebview")
        sys.exit(1)

    url = f"http://{HOST}:{PORT}"
    logging.info(f"打开桌面窗口：{url}")
    webview.create_window("记账本", url, width=980, height=800)
    webview.start()
    # 到这里，PyWebView主循环结束，所有 daemon 线程（Flask）也会被自动杀掉
